<?php


namespace Beerus\Modules\SuperSubsidy\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\SuperSubsidy\YouZanBrandItemModel;
use Biz\model\SuperSubsidy\YouZanBrandUserModel;
use Biz\model\SuperSubsidy\YouZanDeliverRecordModel;
use Biz\model\SuperSubsidy\YouZanOrders;
use Biz\service\SuperSubsidy\YouZanBrand;
use Biz\service\SuperSubsidy\YouZanDeliver;
use Biz\service\SuperSubsidy\YouZanOrder;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use PHPExcel_Cell_DataValidation;
use PhpOffice\PhpSpreadsheet\IOFactory;

class SubsidyBrandDeliverController extends Controller
{
    const PAGE_SIZE = 20;

    public function deliverList(Request $request, Content $content)
    {
        Admin::script($this->reloadDeliverScript());
        $params = $request->all();
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', self::PAGE_SIZE);
        $where = $this->getDeliverCondition($params);
        $res = YouZanDeliver::getDeliverRecord(null, $page, $pageSize, $where);
        $list = $res['list'];
        $total = $res['total'];
        $undoneCount = YouZanDeliverRecordModel::selectCountWhere(['status' => [YouZanDeliverRecordModel::STATUS_CREATE, YouZanDeliverRecordModel::STATUS_DOING]]);
        $brandOption = YouZanBrandUserModel::selectByWhere([], ['id', 'brand_name']);
        $brandOption = array_column($brandOption, 'brand_name', 'id');
        $gridModel = new pGridDataModel($list, $total, ['perPage' => $pageSize]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $brandOption, $undoneCount) {
            $grid->tools(function ($tools) use ($undoneCount) {
                if (HhzEnv::isShopTest() || HhzEnv::isShopHaoHaoCe() || HhzEnv::isGray()) {
                    $tools->append('<div class="btn-group" style="margin-right: 10px">
<a class="btn btn-sm btn-twitter handle-deliver-data" title="处理未完的成发货记录（' . $undoneCount . '）条" href="javascript:void(0);">
<i class="fa fa-refresh"></i><span class="hidden-xs">处理未完的成发货记录（' . $undoneCount . '）条</span></a></div>');
                } else {
                    $tools->append('<div class="btn-group" style="margin-right: 10px">
<span class="hidden-xs" style="color: red">当前未完的成发货记录共（' . $undoneCount . '）条</span></div>');
                }
            });
            $grid->filter(function (Grid\Filter $filter) use ($brandOption) {
                $filter->disableIdFilter();
                $filter->expand();//默认展开
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($brandOption) {
                    $filter->equal('brand_user_id', '品牌账户')->select($brandOption);
                    $filter->equal('record_no', '记录编号');
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->equal('status', '状态')->select(YouZanDeliverRecordModel::STATUS_MAP);
                });
            });
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableBatchActions();
            $grid->fixColumns(2, -2);
            $grid->column('id', 'id');
            $grid->column('record_no', '记录编号');
            $grid->column('brand_user_id', '品牌')->display(function () use ($brandOption) {
                return $brandOption[$this->brand_user_id] ?? '';
            });
            $grid->column('send_num', '发货单数');
            $grid->column('success_num', '成功单数');
            $grid->column('type', '类型')->display(function () {
                return YouZanDeliverRecordModel::TYPE_MAP[$this->type];
            });
            $grid->column('status', '状态')->display(function () {
                $status = YouZanDeliverRecordModel::STATUS_MAP[$this->status];
                if ($this->status == YouZanDeliverRecordModel::STATUS_DONE) {
                    $status .= '｜' . ($this->send_num == $this->success_num ? '成功' : '失败');
                }
                return $status;
            });
            $grid->column('created_at', '提交时间')->display(function () {
                return date('Y-m-d H:i:s', strtotime($this->created_at));
            });;
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
                $actions->disableDelete();
                if ($actions->row->status == YouZanDeliverRecordModel::STATUS_DONE) {
                    $actions->prepend('<a class="fa fa-download" target="_blank" href="' . url('/admin/SuperSubsidy/brand/deliverList/export?record_no=' . $actions->row->record_no) . '">下载发货记录</a>');
                }
                $now = time();
                $createTime = strtotime($actions->row->created_at);
                //超过5分钟还是待处理的记录，支持手工更新
                if (in_array($actions->row->status, [YouZanDeliverRecordModel::STATUS_CREATE, YouZanDeliverRecordModel::STATUS_DOING])
                    && ($now - $createTime) > 300
                ) {
                    $actions->prepend('<a class="fa fa-refresh refresh-deliver" data-id="' . $actions->row->record_no . '" href="javascript:void(0);">处理</a>');
                }
            });
        });
        $tab = new Tab();
        $tab->addLink('超级补贴 | 订单列表', url('/admin/SuperSubsidy/brand/orderList'));
        $tab->add('超级补贴 | 发货记录', $grid->render(), true);
        $content->row($tab);
        return $content
            ->header("超级补贴 | 发货记录")
            ->description(' ')
            ->breadcrumb(['text' => '超级补贴 | 发货记录', 'url' => url('/admin/SuperSubsidy/brand/deliverList')], ['text' => '发货记录']);
    }

    public function deliverExport(Request $request)
    {
        try {
            $recordNo = $request->input('record_no', '');
            YouZanDeliver::exportDeliverRecord($recordNo);
        } catch (\Exception $exception) {
            Log::error('导出异常', $exception);
        }
    }

    private function reloadDeliverScript()
    {
        return <<<SCRIPT
        $('.handle-deliver-data').unbind('click').click(function(){
            let url = '/admin/SuperSubsidy/brand/deliverList/handleDeliver'
            let params = {}
            $.ajaxSettings.async = true;
            $.post(url, params , function (e) {
                 toastr.success(e.title);
                 setTimeout(function () {
                    parent.window.location.reload();
                 }, 2000);
            });
        });
        $('.refresh-deliver').unbind('click').click(function(){
            var id= $(this).data('id');
            let url = '/admin/SuperSubsidy/brand/deliverList/handleDeliver?record_no='+id;
            let params = {};
            $.ajaxSettings.async = true;
            $.post(url, params , function (e) {
                 toastr.success(e.title);
                 setTimeout(function () {
                    parent.window.location.reload();
                 }, 2000);
            });
        });
SCRIPT;
    }

    public function handleDeliver(Request $request)
    {
        try {
            $recordNo = $request->input('record_no', '');
            YouZanDeliver::handleDeliverRecord(false, $recordNo);
            $success = new MessageBag([
                'title' => '已处理'
            ]);
        } catch (\Exception $e) {
            $success = new MessageBag([
                'title' => '处理失败,信息:' . $e->getFile() . $e->getLine() . $e->getMessage()
            ]);
        }
        return response()->json($success);
    }

    public function getDeliverCondition($params)
    {
        $brandUserId = $params['brand_user_id'] ?? null;
        $brandUserId = !empty($brandUserId) ? $brandUserId : null;
        $recordNo = $params['record_no'] ?: '';
        $status = $params['status'] ?? null;
        $status = (strlen($status) > 0) ? $status : null;
        if ($brandUserId) {
            $where['brand_user_id'] = $brandUserId;
        }
        if ($recordNo) {
            $where['record_no'] = $recordNo;
        }
        if (!is_null($status)) {
            $where['status'] = $status;
        }
        $where['ORDER'] = ['id' => 'DESC'];
        return $where;
    }

}